package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.Rest.coupon.bos.CreateCouponBos;
import com.burgeon.backend.Rest.coupon.util.CreateIntegral;
import com.burgeon.backend.Rest.coupon.xe.CreateCoupon;

import com.burgeon.backend.SHOP.entity.couponGift.CouponGiftVO;
import com.burgeon.backend.SHOP.mappers.AppCouponGiftMapper;
import com.burgeon.backend.SHOP.rest.GETUserByOpenid;
import com.burgeon.backend.SHOP.service.AppComplementService;
import com.burgeon.backend.SHOP.service.AppCouponGiftService;
import com.burgeon.backend.SHOP.service.AppTemplateService;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.SHOPBACKEND.entity.couponGift.CouponGiftItem;
import com.burgeon.backend.entity.Coupon;
import com.burgeon.backend.entity.CouponType;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.User;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponMapper;
import com.burgeon.backend.mappers.CouponRestrictMapper;
import com.burgeon.backend.service.ex.ErrorDataException;
import com.burgeon.backend.service.ex.InsertException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class AppCouponGiftServiceImpl implements AppCouponGiftService {

    private final static Log logger = LogFactory.getLog(AppCouponGiftService.class);

    @Autowired
    private AppCouponGiftMapper appCouponGiftMapper;
    @Autowired
    private AppComplementService appComplementService;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private CouponRestrictMapper couponRestrictMapper;
    @Autowired
    private AppTemplateService appTemplateService;
    @Autowired
    private AccountMapper accountMapper;

    private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(8);
/*
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");//消息模板使用
        String dateString = sdf.format(new Date());

        Info info = accountMapper.GetTokenData(token);

//判断vip积分
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            User user = getUserByOpenid.getData(openid);
            if (Integer.parseInt(user.getIntegral())<Integer.parseInt(couponType.getIntegral())){
                throw new ErrorDataExceptionApp("积分不足?快去完成任务");
            }
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }


        */

    private void conversionCoupon
            (String tid, String phone, String openid, String dateString,
             SimpleDateFormat ssdf, String token, Info info) {


        CouponType couponType = couponMapper.findCouponTypeById(tid);


        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        Coupon coupon = new Coupon();
        coupon.setName(couponType.getName());
        coupon.setCode(code);
        coupon.setVipCode(phone);
        coupon.setCreation(dateString);
        coupon.setTypeid(tid);
        coupon.setType(couponType.getType());
        coupon.setDiscount(couponType.getDiscount());
        coupon.setDatebeg(couponType.getDatebeg());
        coupon.setDateend(couponType.getDateend());
        coupon.setIntegral(couponType.getIntegral());
        coupon.setMoney(couponType.getMoney());
        coupon.setOriginal(couponType.getOriginal());
        coupon.setAccount(token);
        coupon.setToken(token);
        String source = "积分兑换";
        coupon.setSource(source);
        String inid = null;
        try {
            if ("BOS".equals(info.getSystem())) {
                CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                inid = createIntegral.getData(phone, couponType.getIntegral());
                coupon.setVipIntegral(inid);
                if (!"1".equals(couponType.getScene())) {
                    List<String> goods = new ArrayList<>();
                    List<String> stores = new ArrayList<>();

                    if (couponType.getRestrictProduct().equals("Y")) {
                        goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

                    }
                    if (couponType.getRestrictStore().equals("Y")) {
                        stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());
                    }

                    createCoupon.getData(coupon, goods, stores);
                }

            } else {
                CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                inid = createIntegral.getData(phone, couponType.getIntegral());
                coupon.setVipIntegral(inid);
                if (!"1".equals(couponType.getScene())) {
                    createCoupon.getData(coupon);
                }

            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "创建优惠券错误" + inid + ";" + phone);
            throw new ErrorDataExceptionApp(e.getMessage());
        }
        Integer row = couponMapper.addCoupon(coupon);

        if (row != 1) {
            logger.error("创建优惠券出错" + inid + ";" + phone);
            throw new ErrorDataException("出现错误");
        }
        coupon.setCreation(ssdf.format(new Date()));
        SimpleDateFormat sdft = new SimpleDateFormat("yyyyMMdd");
        try {
            coupon.setDateend(ssdf.format(sdft.parse(couponType.getDatebeg())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        appTemplateService.SendExchangeCoupon(coupon, phone, openid, token);

    }


    private void createCouponThread
            (List<CouponGiftItem> itmeList, String openid, String phone,
                                    String dateString,
                                    SimpleDateFormat ssdf, String token, Info info) {


        // 2. 创建好Runnable类线程对象 & 需执行的任务
        for (CouponGiftItem couponGiftItem : itmeList) {
            for (int i = 0; i < couponGiftItem.getCount(); i++) {
                Runnable task = () -> {
                    System.out.println("执行任务啦");
                    try {

                        conversionCoupon
                                (couponGiftItem.getTid(),phone,openid,dateString,
                                        ssdf,token,info);

                    } catch (InsertException e) {
                        e.printStackTrace();
                        System.err.println(e.getMessage());

                    }
                };
                // 3. 向线程池提交任务
                fixedThreadPool.execute(task);

            }
        }

    }

    @Override
    public List<CouponGiftVO> conversionData(String token) {
        List<CouponGiftVO> data = appCouponGiftMapper.getCouponGiftVO(token);
        for (CouponGiftVO couponGiftVO : data) {
            couponGiftVO.setCouponTypes(appCouponGiftMapper.getCouponTypeList(couponGiftVO.getId()));
        }
        return data;
    }

    @Override
    public void conversion(String tid, String uid, String openid, String phone, String token) throws ErrorDataExceptionApp {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");//消息模板使用
        String dateString = sdf.format(new Date());
        int integral = 0;
        Info info = accountMapper.GetTokenData(token);

        List<CouponGiftItem> itemList = appCouponGiftMapper.getItemList(tid);

        for (CouponGiftItem couponGiftItem: itemList){
            integral += couponGiftItem.getIntegral();
        }

//判断vip积分
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            User user = getUserByOpenid.getData(openid);
            if (Integer.parseInt(user.getIntegral()) < integral) {
                throw new ErrorDataExceptionApp("积分不足?快去完成任务");
            }
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }

        //执行发券
        createCouponThread(itemList,openid,phone,dateString,ssdf,token,info);

    }


    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }


}
